package com.quickcode.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
public class SemaPhoreExample3 {

    public final static int threadCount = 20;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < threadCount; ++i) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    if (semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS)) {  //如果等待时间获取到了则执行，否则则放弃
                        out(count);
                    } else {
                        log.info("放弃执行.");
                    }
                } catch (InterruptedException e) {
                    log.error("异常：{}",e);
                } finally {
                    semaphore.release();
                }
            });

        }
        executorService.shutdown();
        log.info("finished");
    }

    public static void out(int value) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error("sleep exception:{}", e);
        }
        log.info("value:{}", value);
    }
}
